package com.ksd.quartz.task;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ksd.common.config.PlayControlConfig;
import com.ksd.common.utils.DateUtils;
import com.ksd.common.utils.StringUtils;
import com.ksd.quartz.http.DRMHttpClient;
import com.ksd.quartz.http.NIOFileDownloader;
import com.ksd.quartz.task.beans.SynchApkRequest;
import com.ksd.quartz.task.beans.SynchApkResponse;
import com.ksd.quartz.task.beans.SynchChannelResponse;
import com.ksd.quartz.util.TaskConstans;
import com.ksd.system.domain.SysApkVersion;
import com.ksd.system.domain.SysBoard;
import com.ksd.system.domain.SysContentSynch;
import com.ksd.system.domain.SysFirst;
import com.ksd.system.service.*;
import com.ksd.system.service.impl.AsynchWeatherService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 每隔1小时向云服务器系统查询是否有待升级的终端APK版本,如果有的话,需要将待升级apk下载同步到服务器上
 */
@Component("synchApkVersionTask")
public class SynchApkVersionTask {

    private static final Logger logger = org.slf4j.LoggerFactory.getLogger(SynchApkVersionTask.class);

    @Autowired
    private ISysApkVersionService sysApkVersionService;
    @Autowired
    private ISysBoardService sysBoardService;
    @Autowired
    private ISysContentSynchService sysContentSynchService;
    @Autowired
    private ISysOperLogService sysOperLogService;


    public void getApkVersion()
    {
        SysContentSynch sysContentSynch = sysContentSynchService.selectSysContentSynchById(SysContentSynch.cloudSynchFlag);
        //检查同步待升级的终端APK版本
        SysApkVersion sysApkVersion = new SysApkVersion();
        SynchApkRequest synchApkRequest = new SynchApkRequest();
        synchApkRequest.setOperatorKey(sysContentSynch.getValue1());

        String requestGson = JSONObject.toJSONString(synchApkRequest);

        String url = sysContentSynch.getValue2()+TaskConstans.synchApkVersionUrl;
        logger.info("[system-synchApk] SynchApkVersionTask Interface url :" + url);
        logger.info("[system-synchApk] SynchApkVersionTask Interface Request :" + requestGson);

        String response = DRMHttpClient.udrmHttpDoPost(url, requestGson);

        ObjectMapper mapperPage = new ObjectMapper();
        try {
            logger.info("response:"+response.toString());
            SynchApkResponse synchApkResponse = mapperPage.readValue(response, SynchApkResponse.class);
            logger.info("[system-synchApk] SynchApkVersionTask Interface response :" + synchApkResponse.toString());
            if (StringUtils.isNotNull(synchApkResponse)) {
                sysOperLogService.insertOperlogApiSuccess("终端APK同步接口响应数据:"+response);
                Integer status = synchApkResponse.getStatus();
                if (status == -1){
                    logger.info(synchApkResponse.getMessage());
                    sysOperLogService.insertOperlogApiError("终端APK同步接口响应状态失败:"+status.toString());
                    return;
                }else{
                    //获取最新jar,将终端APKjar包同步到本地
                    String apkPath = synchApkResponse.getApkPath();//该文件地址需要能够通过服务器直接访问到,即在云服务器上已部署在nginx指定目录下
                    String apkName = synchApkResponse.getApkName();
                    String apkVersion = synchApkResponse.getApkVersion();

                    if (StringUtils.isNotEmpty(apkVersion)) {
                        sysApkVersion.setVersion(apkVersion);
                    }
                    sysApkVersion.setType(1);
                    List<SysApkVersion> sysApkVersions = sysApkVersionService.selectSysApkVersionList(sysApkVersion);
                    String dataPath = File.separator+"playcontrol_apk_version"+File.separator+ DateUtils.dateTimeNow();
                    String downPath = PlayControlConfig.getNginxRootPath()+ dataPath+File.separator+apkName;
                    String mappedPath = PlayControlConfig.getMappingPath()+ dataPath+File.separator+apkName;
                    System.out.println("终端APK版本更新下载到服务器地址:"+downPath);
                    System.out.println("终端APK版本更新下载到服务器地址:"+downPath);
                    if (sysApkVersions.size() > 0) {
                        sysApkVersion = sysApkVersions.get(0);
                        if (!sysApkVersion.getCloudPath().equals(apkPath)){
                            logger.info("终端APK升级最新版本:"+apkVersion+"更新下载,将版本更新到服务地址:"+downPath);
                            sysOperLogService.insertOperlogApiSuccess("终端APK升级最新版本:"+apkVersion+"更新下载,将版本更新到服务地址:"+downPath);
                            //将该待升级的终端APKapk下载下来,同时需要下载到指定目录下,即该系统服务器的nginx指定目录下
                           try {
                               boolean flag = NIOFileDownloader.downloadFile(apkPath, downPath);
                               if (flag){
                                   logger.info("终端APK升级文件下载成功,"+downPath);
                                   logger.info("版本更新映射到服务器的地址:"+mappedPath);
                                   sysOperLogService.insertOperlogApiSuccess("终端APK升级文件下载成功,"+downPath+" ,版本更新映射到服务器的地址:"+mappedPath);
                                   //同步升级信息
                                   sysApkVersion.setUrl(mappedPath);
                                   sysApkVersion.setCloudPath(apkPath);

                                   SysContentSynch syschJar = sysContentSynchService.selectSysContentSynchById(SysContentSynch.synch_apk_id);
                                   if (StringUtils.isNotNull(syschJar)) {
                                       syschJar.setValue1(sysApkVersion.getVersion());
                                       sysContentSynchService.updateSysContentSynch(syschJar);
                                   }
                                   sysApkVersionService.updateSysApkVersion(sysApkVersion);
                               }else{
                                   logger.error("终端APK升级文件下载失败,"+downPath);
                                   sysOperLogService.insertOperlogApiError("终端APK升级文件下载失败,"+downPath);
                               }
                            } catch (IOException e) {
                                logger.error("终端APK升级文件下载失败: " + e.getMessage()+" ,待下载的终端APK版本地址:"+apkPath);
                               sysOperLogService.insertOperlogApiError("终端APK升级文件下载失败: " + e.getMessage()+" ,待下载的终端APK版本地址:"+apkPath);
                            }
                        }else{
                            logger.info("终端APK升级版本:"+apkVersion+"已与云服务版本同步,无需下载更新");
                            sysOperLogService.insertOperlogApiSuccess("终端APK升级版本:"+apkVersion+"已与云服务版本同步,无需下载更新");
                        }
                    }else {
                        logger.info("终端APK升级版本:"+apkVersion+",第一次同步,将版本更新到服务地址:"+downPath);
                        sysOperLogService.insertOperlogApiSuccess("终端APK升级版本:"+apkVersion+",第一次同步,将版本更新到服务地址:"+downPath);
                        try {
                            boolean flag = NIOFileDownloader.downloadFile(apkPath, downPath);
                            if (flag){
                                logger.info("终端APK升级文件下载成功:"+downPath);
                                logger.info("版本更新映射到服务器的地址:"+mappedPath);
                                sysOperLogService.insertOperlogApiError("终端APK升级文件下载成功:"+downPath+",版本更新映射到服务器的地址:"+mappedPath);
                                //同步升级信息
                                sysApkVersion.setVersion(apkVersion);
                                sysApkVersion.setCloudPath(apkPath);
                                sysApkVersion.setUrl(mappedPath);
                                sysApkVersion.setType(1); //1apk类型2jar包类型

                                SysContentSynch syschJar = sysContentSynchService.selectSysContentSynchById(SysContentSynch.synch_apk_id);
                                if (StringUtils.isNotNull(syschJar)) {
                                    syschJar.setValue1(sysApkVersion.getVersion());
                                    sysContentSynchService.updateSysContentSynch(syschJar);
                                }
                                sysApkVersionService.insertSysApkVersion(sysApkVersion);
                            }else{
                                logger.error("终端APK升级文件下载失败,"+downPath);
                                sysOperLogService.insertOperlogApiError("终端APK升级文件下载失败,"+downPath);
                            }
                        } catch (IOException e) {
                            logger.error("终端APK升级文件下载失败: " + e.getMessage()+" ,待下载的终端APK版本地址:"+apkPath);
                            sysOperLogService.insertOperlogApiError("终端APK升级文件下载失败: " + e.getMessage()+" ,待下载的终端APK版本地址:"+apkPath);
                        }
                    }
                }
            }else{
                sysOperLogService.insertOperlogApiError("终端APK同步接口响应数据为空.");
            }
        }catch (Exception e){
            e.printStackTrace();
        }


        logger.info("端APK升级文件同步成功====================================end");
    }

    public static void main(String[] args) {
//        String apkPath = "http://192.168.10.244:8080/storage/upload/videos/zipFile/20250418143048//终端APK升级包/tvlanucher-release.v5.7.40.apk";
        String apkPath ="http://192.168.10.244:8080//storage/upload/videos/zipFile/20250418143048//终端APK升级包/tvlanucher-release.v5.7.40.apk";
        String downPath ="D:\\playservice\\云服务器升级数据\\apk_version\\versionCheckTemp.apk";
        try {
            boolean flag = NIOFileDownloader.downloadFile(apkPath, downPath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
